namespace TXLooker.WorkItemExtention.WIQL
{
    using System;

    public class NodeCondition : NodeList
    {
        private Condition m_condition;

        public NodeCondition() : base(NodeType.FieldCondition, 2)
        {
        }

        public NodeCondition(Condition condition, NodeFieldName left, Node right) : this()
        {
            this.m_condition = condition;
            this.Left = left;
            this.Right = right;
        }

        public override void Bind(IExternal e, NodeTableName tableContext, NodeFieldName fieldContext)
        {
            this.Left.Bind(e, tableContext, fieldContext);
            this.Right.Bind(e, tableContext, this.Left);
            Tools.EnsureSyntax(this.Right.IsConst, SyntaxError.ExpectingConst, this.Right);
            if (e != null)
            {
                Tools.EnsureSyntax(this.Right.CanCastTo(this.Left.DataType, e.CultureInfo), SyntaxError.IncompatibleRightConst, this);
            }
            if ((e != null) && (this.Condition == Condition.Contains))
            {
                Tools.EnsureSyntax(this.Left.DataType == DataType.String, SyntaxError.ContainsWorksForStringsOnly, this);
            }
            base.Bind(e, tableContext, fieldContext);
        }

        public override Node Optimize(IExternal e, NodeTableName tableContext, NodeFieldName fieldContext)
        {
            this.Left = (NodeFieldName) this.Left.Optimize(e, tableContext, fieldContext);
            this.Right = this.Right.Optimize(e, tableContext, this.Left);
            return base.Optimize(e, tableContext, fieldContext);
        }

        public override string ToString()
        {
            return base.JoinChildren(" " + ConditionalOperators.GetString(this.m_condition) + " ");
        }

        public Condition Condition
        {
            get
            {
                return this.m_condition;
            }
            set
            {
                this.m_condition = value;
            }
        }

        public override DataType DataType
        {
            get
            {
                return DataType.Bool;
            }
        }

        public NodeFieldName Left
        {
            get
            {
                return (NodeFieldName) this[0];
            }
            set
            {
                this[0] = value;
            }
        }

        public override Priority Priority
        {
            get
            {
                return Priority.ConditionalOperator;
            }
        }

        public Node Right
        {
            get
            {
                return this[1];
            }
            set
            {
                this[1] = value;
            }
        }
    }
}

